<?php

namespace App\Traits;

use EasySwoole\EasySwoole\Logger;
use EasySwoole\Log\LoggerInterface;

trait LogTrait
{
    protected function exception_debug(\Exception $exception)
    {
        Logger::getInstance()->debug(static::exception_message($exception));
    }

    protected function log_debug($msg)
    {
        Logger::getInstance()->debug(static::log_message($msg));
    }

    protected function exception_info(\Exception $exception)
    {
        Logger::getInstance()->info(static::exception_message($exception));
    }

    protected function log_info($msg)
    {
        Logger::getInstance()->info(static::log_message($msg));
    }

    protected function exception_notice(\Exception $exception)
    {
        Logger::getInstance()->notice(static::exception_message($exception));
    }

    protected function log_notice($msg)
    {
        Logger::getInstance()->notice(static::log_message($msg));
    }

    protected function exception_warning(\Exception $exception)
    {
        Logger::getInstance()->waring(static::exception_message($exception));
    }

    protected function log_warning($msg)
    {
        Logger::getInstance()->waring(static::log_message($msg));
    }

    protected function exception_error(\Exception $exception)
    {
        Logger::getInstance()->error(static::exception_message($exception));
    }

    protected function log_error($msg)
    {
        Logger::getInstance()->error(static::log_message($msg));
    }

    protected function exception_console(\Exception $exception)
    {
        Logger::getInstance()->console(static::exception_message($exception), LoggerInterface::LOG_LEVEL_DEBUG);
    }

    protected function log_console($msg, $loggerInterface_level)
    {
        Logger::getInstance()->console(static::log_message($msg), $loggerInterface_level);
    }

    private function exception_message(\Exception $e)
    {
        $msg = '';
        $msg .= "- 文件名：**{$e->getFile()}** \n";
        $msg .= "- 第几行：**{$e->getLine()}** \n";
        $msg .= "- 错误信息：**{$e->getMessage()}**\n";
        return $msg;
    }

    private function log_message($message): string
    {
        $debugInfo = debug_backtrace();
        $head = $debugInfo[1]['file']. '('.$debugInfo[1]['line'].') ';
        return $head.$message;
    }
}
